//
//  LHNetWorkManager.swift
//  SinaWeibo
//
//  Created by 美食家 on 17/4/3.
//  Copyright © 2017年 不孤独的美食家. All rights reserved.
//

import UIKit
import AFNetworking


///请求类型
enum LHHTTPRequestMethodType {
    case GET
    case POST
}

/// 网络工具单例类
class LHNetWorkManager: AFHTTPSessionManager {

    static let shared : LHNetWorkManager={
        let instance = LHNetWorkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
//    ///访问令牌，所有网络请求都基于此令牌（登录除外）,token有时间限制，默认三天2.00v8tSKEFNuyRC7cd798cc0eDMKCKD
//    var accessToken : String? // = "2.00v8tSKEGdgIAD0b8d8c538d0GidEK"
//    ///微博用户的UID
//    var uid : String? = "2097979131"
    
    ///用户模型的懒加载
    lazy var userAccount = WBUserAccount()
    
    /** 用户登陆标识 */
    var userLogon : Bool{
        return userAccount.access_token != nil
    }

    
    ///专门负责处理token的网络请求方法
    func tokenRequest(Method:LHHTTPRequestMethodType = .GET,urlString:String,parameters:[String:AnyObject]?,completion:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->()) -> Void {
        
        guard let token=userAccount.access_token    else{
                 completion(nil,false)
            //FIXME: 发送通知，提示用户登陆
            print("access_Token为空，需要重新登录")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification),
                                            object: "Bad Token"
                                            )
                 return
        }
        
        var parameters=parameters
        
        if parameters==nil{
        
            parameters=[String : AnyObject]()
        }
        
        parameters!["access_token"]=token as AnyObject?
        
        
        request(urlString: urlString, parameters: parameters!, completion: completion)
    }
    
    func request(Method:LHHTTPRequestMethodType = .GET,urlString:String,parameters:[String:AnyObject],completion:@escaping (_ json:AnyObject?,_ isSuccess:Bool)->()) {
        
        let success = { (task:URLSessionDataTask,json:Any?) ->() in
            completion(json as AnyObject?,true)
        }
        
        let failure = { (task:URLSessionDataTask?,error:Error)->()  in
           
           if (task?.response as! HTTPURLResponse).statusCode == 403{
            
            //FIXME: 发送通知，谁收到谁处理，提醒用户再次登陆
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification),
                                            object:nil
                                            )
            
            }
             print("\(error)")
            completion(nil,false)
        }
        
        
        /** 可能遇到的问题：Cannot convert value of type '(URLSessionDataTask?, NSError) -> ()' to expected argument type '((URLSessionDataTask?, Error) -> Void)?' */
        /** 将NSError转换成Error,参考链接：http://stackoverflow.com/questions/39640029/afnetwoking-with-swift-3-0-xcode-8-post-request-get-request */
        if Method == .GET{
            get(urlString, parameters: parameters, progress: nil, success:success, failure:failure)
        }else{
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
